package com.yoshino.usercenter.utils;

import cn.hutool.core.util.RandomUtil;
import com.yoshino.usercenter.exception.BusinessException;
import com.yoshino.yoshinoapicommon.common.ErrorCode;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.SimpleEmail;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

/**
 * 邮件工具
 *
 * @author yoshino
 **/
@Component
public class EmailUtils {

    @Resource
    RedisTemplate<String, Object> redisTemplate;

    public static boolean isValidEmail(String email) {
        if ((email != null) && (!email.isEmpty())) {
            return Pattern.matches("^(\\w+([-.][A-Za-z0-9]+)*){3,18}@\\w+([-.][A-Za-z0-9]+)*\\.\\w+([-.][A-Za-z0-9]+)*$", email);
        }
        return false;
    }

    //发送验证码
    public void sendEmail(String registerEmail) {
        // 重复点击(120s之内)
        Object has = redisTemplate.opsForValue().get(registerEmail);
        if (has != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "重复点击");
        }
        //随机数用作验证
        String userVerificationCode = RandomUtil.randomNumbers(6);
        try {
            SimpleEmail email = new SimpleEmail();
            // 发送邮件的服务器
            email.setHostName("smtp.qq.com");
            // 授权
            email.setAuthentication("1344200478@qq.com", "ayrekuxdkafvggbi");
            // 发送邮件的邮箱和发件人
            email.setFrom("1344200478@qq.com", "yoshino");
            // 使用安全连接
            email.setSSLOnConnect(true);
            email.addTo(registerEmail);
            email.setSubject("注册验证码");
            String msg = "您好！" + registerEmail + ",您正在使用邮箱验证，验证码：" + userVerificationCode + "。";
            email.setMsg(msg);
            email.send();
        } catch (EmailException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "发送邮件失败，请核对邮箱账号");
        }
        //下面是加入缓存，以便于进行邮箱验证
        redisTemplate.opsForValue().set(registerEmail, DigestUtils.md5DigestAsHex(userVerificationCode.getBytes()), 70, TimeUnit.SECONDS);
    }

    /**
     * 验证验证码
     */
    public boolean checkEmail(String registerEmail, String code) {
        Object obj = redisTemplate.opsForValue().get(registerEmail);
        if (obj == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码已过期");
        }
        String md5Code = DigestUtils.md5DigestAsHex(code.getBytes());
        return md5Code.equals(obj);
    }

}
